package com.candy.candymessagerpc.config;

import com.candy.candycommon.Event.ApplicationStartedEventListener;
import com.candy.candymessagerpc.bean.Message;
import com.candy.candymessagerpc.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.annotation.Resource;
import java.net.InetAddress;

/**
 * @author suYanLong
 * @version 1.0
 * @date 2023/6/5 15:12
 * @Description 应用启动成功之后处理
 */
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "rpc", name = "message.startedEvent.enable", havingValue = "true", matchIfMissing = false)
public class ApplicationStartedEventConfig {

    @Resource
    MessageService messageService;

    @Resource
    RpcMessageProperty rpcMessageProperty;

    @Resource
    Environment environment;

    /**
     * TODO 待项目启动成功之后，发布一个应用启动成功的消息
     *  未处理完
     *
     * @return
     */
    @Bean
    public ApplicationStartedEventListener exceptionEventListener() {
        System.out.println("sss");
        return new ApplicationStartedEventListener(event -> {
            log.debug("消息服务监听到项目启动消息：{}", event);
            //不是若以系统可以使用
            String name = environment.getProperty("spring.application.name");
            String ip = InetAddress.getLocalHost().getHostAddress();
            String port = environment.getProperty("server.port");
            //本机IP地址+端口号
            if (rpcMessageProperty.getStartedEvent().getEnable()) {
                Message message = new Message(rpcMessageProperty.getStartedEvent().getMsgTypeEnum().getCode(), "【服务上线】" + name + "-" + ip + ":" + port);
                messageService.send(message);
            }
        });
    }

}
